package com.google.code.opengw.server.initializer;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.code.opengw.policy.PolicyUser;
import com.google.code.opengw.server.Constants;
import com.google.code.opengw.server.DataStore;
import com.google.code.opengw.server.Server;
import com.google.code.opengw.server.support.XMLParser;
import com.google.code.opengw.support.OpenGWException;

class UserInitializer {
	
	void initialize() throws ParserConfigurationException, SAXException, IOException, OpenGWException {

		
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

		/*
		 * START OF user-list.xml PARSING and INITIALIZATION
		 */

		Server server = Server.getInstance();
		DataStore dataStore = DataStore.getInstance();
		
		
		Document doc = docBuilder.parse(server.getUserListXML());
		doc.getDocumentElement().normalize();

		Node userListNode = XMLParser.getFirstNodeFromDoc(doc,
				Constants.USER_LIST_FILE_USER_LIST,
				Server.USER_LIST_FILE_NAME, true);

		NodeList userNodeList = ((Element) userListNode)
				.getElementsByTagName(Constants.USER_LIST_FILE_USER);
		for (int i = 0; i < userNodeList.getLength(); i++) {
			Node userNode = userNodeList.item(i);
			String username = ((Element) userNode)
					.getAttribute(Constants.USER_LIST_FILE_USERNAME);
			if (username == null || username.equals(""))
				throw new OpenGWException(OpenGWException.ATTRIBUTE_NOT_FOUND,
						Constants.USER_LIST_FILE_USER,
						Constants.USER_LIST_FILE_USERNAME,
						Server.USER_LIST_FILE_NAME);
			String password = ((Element) userNode)
					.getAttribute(Constants.USER_LIST_FILE_PASSWORD);
			if (password == null || password.equals(""))
				throw new OpenGWException(OpenGWException.ATTRIBUTE_NOT_FOUND,
						Constants.USER_LIST_FILE_USER,
						Constants.USER_LIST_FILE_PASSWORD,
						Server.USER_LIST_FILE_NAME);
			String userRoles = ((Element) userNode)
					.getAttribute(Constants.USER_LIST_FILE_USER_ROLES);

			dataStore.addPolicyUser(new PolicyUser(username, password,
					userRoles));

		}

		/*
		 * END OF user-list.xml PARSING and INITIALIZATION
		 */
	}
}
